package com.ajc.seata.service;

import com.ajc.seata.entity.bank1.AccountInfoBank1;
import com.ajc.seata.entity.bank2.AccountInfoBank2;
import com.ajc.seata.repository.bank1.AccountRepositoryBank1;
import com.ajc.seata.repository.bank2.AccountRepositoryBank2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.transaction.*;

/**
 * @Author: AnJunchao
 * @Description:
 * @Date: Create in 2019-10-12 10:48:54
 * @Modified By:
 */
@Service
@Slf4j
public class BankService {
    @Autowired
    private AccountRepositoryBank1 accountRepositoryBank1;
    @Autowired
    private AccountRepositoryBank2 accountRepositoryBank2;
    @Transactional(rollbackFor = Exception.class)
    public  String updateBankofAccount(Double amount)  {
        //张三账户减少余额
        AccountInfoBank1 accountInfoBank1 = accountRepositoryBank1.findById(2L).get();
        accountInfoBank1.setAccountBalance(accountInfoBank1.getAccountBalance()-amount);
        AccountInfoBank1 save = accountRepositoryBank1.saveAndFlush(accountInfoBank1);
        if(amount==2){
            throw new RuntimeException("张三账户无法减少余额,访问失败");

        }
        //李四账户增加余额
        AccountInfoBank2 accountInfoBank2 = accountRepositoryBank2.findById(3L).get();
        accountInfoBank2.setAccountBalance(accountInfoBank2.getAccountBalance()+amount);
        AccountInfoBank2 accountInfoBank21 = accountRepositoryBank2.saveAndFlush(accountInfoBank2);
        if(amount==3){
            throw new RuntimeException("李四账户无法减少余额,访问失败");
        }
    return "success";
    }
}
